<?php


namespace App\Service;

use App\Utils\CustomUtils;
use Hyperf\Utils\Arr;
use Swlib\SaberGM;

/**
 * Class RiskSyncService
 *
 * @package App\Service
 */
class RiskSyncService {

    const TIME_OUT = 5;

    /**
     * 商户-通道限额使用情况
     *
     * @param $channelNo
     *
     * @return array
     * @throws \Exception
     */
    public function getChannelCost ($channelNo) {

        $api = env('API_RISK').'/sync/getChannelCost';

        $data = [
            'channelNo' => $channelNo,
        ];

        return $this->_requestOrFail($api, $data);
    }

    /**
     * 商户-通道限额使用情况
     *
     * @param $channelNo
     * @param $mchNo
     *
     * @return array
     * @throws \Exception
     */
    public function getMchChannelCost ($channelNo, $mchNo) {

        $api = env('API_RISK').'/sync/getMchChannelCost';

        $data = [
            'channelNo' => $channelNo,
            'mchNo'     => $mchNo,
        ];

        return $this->_requestOrFail($api, $data);
    }


    /**
     * 刷新通道/通道集合
     *
     * @param $channelNoList
     *
     * @return array
     * @throws \Exception
     */
    public function syncChannelCollection ($channelNoList) {

        $api = env('API_RISK').'/sync/channelCollection';

        $conn = [];
        foreach ($channelNoList as $channelNo) {
            $conn[] = ['channelNo' => $channelNo];
        }

        $data = ['conn' => $conn];

        return $this->_requestOrFail($api, $data);
    }

    /**
     * 刷新商户通道
     *
     * @param $mchNo
     *
     * @return array
     * @throws \Exception
     */
    public function syncChannelCollectionMchRef ($mchNo) {

        $api = env('API_RISK').'/sync/channelCollectionMchRef';

        $data = ['mchNo' => $mchNo];

        return $this->_requestOrFail($api, $data);
    }

    /**
     * @param $api
     * @param $data
     *
     * @return array
     * @throws \Exception
     */
    protected function _requestOrFail ($api, $data) {

        $re = null;

        try {
            $re = SaberGM::post($api, $data, ['timeout' => self::TIME_OUT])->getBody()->getContents();
            $re = json_decode($re, true);
        } catch (\Throwable $e) {
        }

        CustomUtils::xzxDebug([
            '通知风控模块更新',
            'api'  => $api,
            'data' => $data,
            're'   => $re,
        ]);

        if (!$re) {
            throw new \Exception('风控模块未响应');
        }

        if (CustomUtils::isError($re)) {
            throw new \Exception($re['message']);
        }

        return CustomUtils::buildSuccess(Arr::get($re, 'data', []), Arr::get($re, 'message', 'success'));
    }

}
